package co.edu.usbcali.adt.exercises.translator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

public class DictionaryPersistence {
	
	public static void saveDictionary(Dictionary dictionary,String fileName){
		try{
			// Create file 
			FileWriter fstream = new FileWriter(fileName);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(dictionary.getLanguage());
			out.newLine();
			int s=dictionary.getSize();
			for(int i=0;i<s;i++){
				String[] pareja=dictionary.equivalences(i);
				out.write(pareja[0]+","+pareja[1]);
				out.newLine();
			}
			//Close the output stream
			out.close();
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}

	public static Dictionary readDictionary(String fileName){
		try{
			// Open the file that is the first 
			// command line parameter
			FileInputStream fstream = new FileInputStream(fileName);
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			strLine = br.readLine();
			Dictionary dictionary=new Dictionary(strLine);
			//Read File Line By Line
			while ((strLine = br.readLine()) != null)   {
			//	System.out.println (strLine);
				String[] words=strLine.split(",");
				dictionary.addWord(words[0], words[1]);
				// Print the content on the console
			}
			//Close the input stream
			in.close();
			return dictionary;
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
			return null;
		}
	}

}
